const db = wx.cloud.database(); // 初始化数据库
Page({
  data: {
    showAddress: false,
    showTag: false,
    addresslist: ['佛山校区', '广州校区'],
    addressresult: [],
    leguetags: ['校级','院级','社联协会','志愿服务','组织策划','技能学习','体育运动','学术交流','宣传制作','音乐舞蹈','行政办公','实践DIY'],
    leguetagresult: [],
    lifeImages: [],
    consultImages: [],
    legueName: '',
    introduction: '',
    demand: '无',
    qq: '',
    weixin: '',
    username: '',
    class: '',
    phone:'',
    email: '',
    lifeImagesIds: [],
    consultImagesIds: [],
    like: 10,

  },
  onNameChange(event) {
    this.setData({
      legueName: event.detail
    })
  },
  onIntroductionChange(event) {
    this.setData({
      introduction: event.detail
    })
  },
  onQQChange(event) {
    this.setData({
      qq: event.detail
    })
  },
  onDemandChange(event) {
    this.setData({
      demand: event.detail
    })
  },
  onUserNameChange(event) {
    this.setData({
      username: event.detail
    })
  },
  onClassChange(event) {
    this.setData({
      class: event.detail
    })
  },
  onPhoneChange(event) {
    this.setData({
      phone: event.detail
    })
  },
  onWeixinChange(event) {
    this.setData({
      weixin: event.detail
    })
  },
  onEmaliChange(event) {
    this.setData({
      email: event.detail
    })
  },
  addressChange(event) {
    this.setData({
      addressresult: event.detail
    });
  },
  tagChange(event) {
    if(event.detail.length <= 3) {
      this.setData({
        leguetagresult: event.detail,
      });
    } else {
      wx.showToast({
        icon: 'none',
        title: '最多选取三个',
      })
    }

  },
  addressToggle(event) {
    const { index } = event.currentTarget.dataset;
    const checkbox = this.selectComponent(`.addressbox-${index}`);
    checkbox.toggle();
  },
  tagsToggle(event) {
    const { index } = event.currentTarget.dataset;
    const checkbox = this.selectComponent(`.tagsbox-${index}`);
    checkbox.toggle();
  },
  noop() {},
  showAddressPopup() {
    this.setData({showAddress:true})
  },
  showTagPopup() {
    this.setData({ showTag: true });
  },
  popupClose() {
    this.setData({ showAddress: false })
    this.setData({ showTag: false });
  },
  afterlifeRead(event) {
    const { file } = event.detail;

    this.data.lifeImages.push({ url: event.detail.file.path })
    this.setData({
      lifeImages: this.data.lifeImages
    })
  },
  deletelifeImage(event) {
    this.data.lifeImages.splice(event.detail.index, 1)
    this.setData({
      lifeImages: this.data.lifeImages
    })
  },
  afterconsultRead(event) {
    const { file } = event.detail;
    this.data.consultImages.push({ url: event.detail.file.path })
    this.setData({
      consultImages: this.data.consultImages
    })
  },
  deleteconsultImage(event) {
    this.data.consultImages.splice(event.detail.index, 1)
    this.setData({
      consultImages: this.data.consultImages
    })
  },
  submit() {
    if(this.data.qq != ''){
      var rsNum= /^\d+$/.test(this.data.qq);
      if(!rsNum) {
        setTimeout(()=>{
          wx.showToast({
              title: 'QQ群号只能是数字',
              icon: 'none'
          })
        },500)
        return
      }
    }
    var phonenum = /^\d+$/.test(this.data.phone)
    if(this.data.legueName == '') {
      wx.showToast({
        icon :'none',
        title: '社团名字不能为空',
      })
    }
    else if(this.data.addressresult.length == 0) {
      wx.showToast({
        icon :'none',
        title: '至少选择一个校区',
      })
    }
    else if(this.data.leguetagresult.length == 0) {
      wx.showToast({
        icon :'none',
        title: '至少选择一个属性',
      })
    }
    else if(this.data.username == '') {
      wx.showToast({
        icon :'none',
        title: '负责人不能为空',
      })
    }
    else if(this.data.class == '') {
      wx.showToast({
        icon :'none',
        title: '班级不能为空',
      })
    }
    else if(this.data.phone == '') {
      wx.showToast({
        icon :'none',
        title: '手机不能为空',
      })
    }
    else if(this.data.email == '') {
      wx.showToast({
        icon :'none',
        title: '邮箱不能为空',
      })
    }
    else if(!phonenum) {
      setTimeout(()=>{
        wx.showToast({
            title: '手机格式不正确',
            icon: 'none'
        })
      },500)
    }
    else {
      var _this = this
      wx.showModal({
        title:'发布提示',
        content: '你确定要发布此条记录吗？发布成功后需要通过审核，审核通过后如需修改，请到【广财小站】公众号按照提示操作。',
        
        success (res) {
          
          if (res.confirm) {
            wx.showLoading({
              title:'发布中'
            })
            // 上传图片到云存储
            let promiseArr = [];
            for (let i = 0; i < _this.data.lifeImages.length; i++) {
              promiseArr.push(new Promise((reslove, reject) => {
                let item = _this.data.lifeImages[i].url;
                let suffix = /\.\w+$/.exec(item)[0]; // 正则表达式，返回文件扩展名
                wx.cloud.uploadFile({
                  cloudPath: new Date().getTime() + suffix, // 上传至云端的路径
                  filePath: item, // 小程序临时文件路径
                  success: res => {
                    // 返回文件ID
                    _this.setData({
                      lifeImagesIds: _this.data.lifeImagesIds.concat(res.fileID)
                    });
                    reslove();
                  },
                  fail: console.error
                })
              }));
            }
            for (let i = 0; i < _this.data.consultImages.length; i++) {
              promiseArr.push(new Promise((reslove, reject) => {
                let item = _this.data.consultImages[i].url;
                let suffix = /\.\w+$/.exec(item)[0]; // 正则表达式，返回文件扩展名
                wx.cloud.uploadFile({
                  cloudPath: new Date().getTime() + suffix, // 上传至云端的路径
                  filePath: item, // 小程序临时文件路径
                  success: res => {
                    // 返回文件 ID
                    _this.setData({
                      consultImagesIds: _this.data.consultImagesIds.concat(res.fileID)
                    });
                    reslove();
                  },
                  fail: console.error
                })
              }));
            }

            Promise.all(promiseArr).then(res => {
              // 插入数据
              db.collection('legue').add({
                data: {
                  legueName: _this.data.legueName,
                  introduction: _this.data.introduction,
                  addressresult: _this.data.addressresult,
                  leguetagresult: _this.data.leguetagresult,
                  demand: _this.data.demand,
                  username: _this.data.username,
                  class: _this.data.class,
                  phone:_this.data.phone,
                  qq: _this.data.qq,
                  weixin: _this.data.weixin,
                  email: _this.data.email,
                  lifeImagesIds: _this.data.lifeImagesIds,
                  consultImagesIds: _this.data.consultImagesIds,
                  like: _this.data.like,
                  status: 0
                }
              }).then(res=>{
                wx.hideLoading();
                wx.showToast({
                  title: '发布成功',
                  duration: 3000,
                  success: function () {
                  setTimeout(function () {
                      wx.reLaunch({
                        url: '../legue/legueintroduction',
                      })
                    }, 2000);
                  }
                 })
              }).catch(err=>{
                wx.hideLoading();
                wx.showToast({
                  title: '发布失败',
                })
              })
        
            });
          } else if (res.cancel) {
          }
        }
      })
      
    }
  }
});